// pages/login/login.js
var app = getApp();
var loginUtils = require("../../utils/loginUtil.js")
var mail_url = "https://www.hkzhaoscut.top/doctor/getvalidcode"
var register_url = "https://www.hkzhaoscut.top/doctor/register"
var doctor_login_url = "https://www.hkzhaoscut.top/doctor/login"
var manager_login_url = "https://www.hkzhaoscut.top/manage/login"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    second: 60, //用于倒计时60s
    alreadySubmit: false, //是否已经提交form
    sendCaptcha: false, //是否发送验证码
    wrongPwd: 0, //错误的密码次数
    navbar: 0, //0表示登录 1表示医生登录 2表示医生注册
    mail: '',
    password: '',
    username: '',
    captcha: '',
    keshi: '', //科室
    danwei: '', //单位
    workerId: '', //工作号
    identify: '', //身份证号
    userType: ['医生', '管理员'], //选择管理员登录还是医生登录
    userTypeId: null, //0代表医生
    type: ['用户登录', '密码登录', '医生注册'],
    userToken: ''
  },

  choseBar(e) {
    var index = e.currentTarget.dataset.index
    this.setData({
      navbar: index
    })
  },
  // 微信授权登录
  wxLogin(res) {
    var a = wx.getStorageSync("userInfo")
    if (a.userToken == null) {
      var that = this
      // 调用loginUtil中的promise风格函数
      var promise1 = new Promise((resolve, rejected) => {
        loginUtils.userLogin("test").then(function(usertoken) {
          that.setData({
            userToken: usertoken
          })
          resolve()
        }, function() {
          console.log("错误")
        });
      })
      promise1.then(() => {
        // 获取用户信息
        var avatarUrl = res.detail.userInfo.avatarUrl
        var userName = res.detail.userInfo.nickName
        var userToken = that.data.userToken
        // console.log("用户的token为",userToken)
        app.globalData.userToken = userToken
        app.globalData.userName = userName
        app.globalData.loginStauts = true
        app.globalData.avatarUrl = avatarUrl
        app.globalData.userType = "user"

        var userInfo = {
          userToken: userToken,
          userName: userName,
          loginStauts: true,
          avatarUrl: avatarUrl,
          userType: "user"
        }
        // 保存到本地
        wx.setStorage({
          key: 'userInfo',
          data: userInfo,
        })
        // 跳转到个人页面
        setTimeout(this.jumpToPerson,500) 
      }, () => {
        console.log("rejected")
      })
    } else {
      // 跳转到个人页面
      app.globalData.loginStauts = true
      app.globalData.userType = "user"
      app.globalData.avatarUrl = a.avatarUrl
      setTimeout(this.jumpToPerson, 500) 
    }
  },

  // 医生和管理员登录的按钮
  submitLogin(e) {
    var that = this
    var pwd = e.detail.value.password
    var username = e.detail.value.username
    var userTypeId = that.data.userTypeId
    // console.log(username,pwd)
    if (userTypeId == null) {
      wx.showToast({
        title: '请选择登录角色！',
        icon: 'none',
      })
    } else {
      // console.log(pwd.length, usrname.length)
      if (pwd.length != 0 && username.length != 0) {
        // 这里向后台发送登录请求
        // 如果密码错误次数超过3次，开启倒计时
        // wrongPwd++
        // alredySubmit=true
        // second=30

        // 设置的保存本地的函数都写在回调函数中，重构困难，硬着头皮写把QAQ
        // 0表示医生，1表示管理员
        if (userTypeId == 0) {
          wx.request({
            url: doctor_login_url,
            method: "POST",
            data: {
              username: username,
              password: pwd
            },
            success(res) {
              console.log(res)
              var code = res.data.code
              if (code == 200) {
                var token = res.data.data.tokenHead + ' ' + res.data.data.token
                app.globalData.userName = username
                app.globalData.loginStauts = true
                app.globalData.doctorToken = token
                app.globalData.userType = "doctor"
                // 保存信息到本地
                var userInfo = {
                  doctorToken: token,
                  userName: username,
                  loginStauts: true,
                  userType: "doctor"
                }
                // 保存到本地
                wx.setStorageSync('userInfo', userInfo)
                setTimeout(that.jumpToPerson, 500)
              } else {
                var message = res.data.message
                wx.showToast({
                  title: message,
                  icon: 'none',
                })
              }
            }
          })
        } else {
          wx.request({
            url: manager_login_url,
            method: "POST",
            data: {
              username: username,
              password: pwd
            },
            success(res) {
              console.log(res)
              var code = res.data.code
              if (code == 200) {
                var token = res.data.data.tokenHead + ' ' + res.data.data.token
                app.globalData.userName = username
                app.globalData.loginStauts = true
                app.globalData.managerToken = token
                app.globalData.userType = "manager"
                // 保存信息到本地
                var userInfo = {
                  managerToken: token,
                  userName: username,
                  loginStauts: true,
                  userType: "manager"
                }
                // 保存到本地
                wx.setStorageSync('userInfo', userInfo)
                setTimeout(that.jumpToPerson, 500)
              } else {
                var message = res.data.message
                wx.showToast({
                  title: message,
                  icon: 'none',
                })
              }
            }
          })
        }


      } else {
        wx.showToast({
          title: '密码或用户名不能为空！',
          icon: "none"
        }, 500)
      }
    }
  },
  // // 用户注册的按钮
  // submitUserRegister(e){
  //   var pwd=e.detail.value.password
  //   var usrname=e.detail.value.username
  //   var captcha=e.detail.value.captcha
  //   if (pwd.length!=0 && usrname.length!=0 && captcha.length!=0 ){
  //     // 这里向后台发送用户注册请求

  //   }else{
  //     if (captcha.length==0){
  //       wx.showToast({
  //         title: '验证码不能为空！',
  //         icon:"none"
  //       },500)
  //     }else{
  //       wx.showToast({
  //         title: '密码或用户名不能为空！',
  //         icon: "none"
  //       }, 500)
  //     }
  //   }
  // },
  //医生注册的按钮
  submitDoctorRegister(e) {
    // console.log(e)
    var that = this
    var email = this.data.mail
    var pwd = e.detail.value.password
    var username = e.detail.value.username
    var captcha = e.detail.value.captcha
    var danwei = e.detail.value.danwei
    var keshi = e.detail.value.keshi
    var workerId = e.detail.value.workerId
    var identify = e.detail.value.identify
    if (pwd.length != 0 && username.length != 0 && captcha.length != 0 && keshi.length != 0 && danwei.length != 0 && workerId.length != 0 && identify.length != 0) {
      // 这里向后台发送用户注册请求
      wx.request({
        url: register_url,
        data: {
          username: username,
          password: pwd,
          Worder_id: workerId,
          Identify_id: identify,
          Doctor_type: keshi,
          Province: danwei,
          email: email,
          ValidCode: captcha
        },
        success(res) {
          console.log(res)
          if (res.data.code == "200") {
            wx.showToast({
              title: '注册成功，正在审核！',
              icon: "none",
            })
            // setTimeout(that.jumpToPerson,500)
          } else if (res.data.code == "500") {
            var message = res.data.message
            wx.showToast({
              title: message,
              icon: "none",
            }, 500)
          } else {
            wx.showToast({
              title: '网络错误，清稍后重试！',
              icon: "none",
            }, 500)
          }
        }
      })

    } else {
      if (captcha.length == 0) {
        wx.showToast({
          title: '验证码不能为空！',
          icon: "none"
        }, 500)
      } else if (pwd.length == 0 || username.length == 0) {
        wx.showToast({
          title: '密码或用户名不能为空！',
          icon: "none"
        }, 500)
      } else if (keshi.length == 0 || danwei.length == 0) {
        wx.showToast({
          title: '请输入单位地区和医生类型！',
          icon: "none"
        }, 500)
      } else {
        wx.showToast({
          title: '请输入工作号和身份证号！',
          icon: "none"
        }, 500)
      }
    }
  },
  //注册、登录成功后跳转函数
  jumpToPerson() {

    wx.navigateBack({

    })
  },
  // 选择登录角色
  userTypePicker(e) {
    // console.log(e)
    this.setData({
      userTypeId: e.detail.value
    })
  },
  // 发送邮箱验证码
  sendMail(e) {
    // js正则匹配邮箱格式
    var myreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
    var mailAddr = this.data.mail
    if (myreg.test(mailAddr)) {
      // 这里向后台发送验证码请求
      // 30s可以发送一次
      wx.request({
        url: mail_url,
        data: {
          email: mailAddr
        },
        success(res) {
          console.log("邮箱验证码为:", res.data)
        }
      })

      this.setData({
        sendCaptcha: true,
        second: 30
      })
      this.timer()
    } else {
      wx.showToast({
        title: '请输入正确的邮箱地址！',
        icon: "none"
      }, 500)
    }
  },
  // 监听邮箱input即时改变mail
  mailInput(e) {
    this.setData({
      mail: e.detail.value
    })
  },
  // 倒计时函数
  timer: function() {
    var second = 0
    let promise = new Promise((resolve, reject) => {
      let setTimer = setInterval(
        () => {
          this.setData({
            second: this.data.second - 1
          })
          if (this.data.second <= 0) {
            this.setData({
              second: second,
              alreadySubmit: false,
              sendCaptcha: false,
            })
            resolve(setTimer)
          }
        }, 1000)
    })
    promise.then((setTimer) => {
      clearInterval(setTimer)
    })
  },
  // onLoad函数
  onLoad(e) {
    var navbar = e.navbar
    this.setData({
      navbar: navbar
    })
  }
})